package cn.iocoder.yudao.module.member.service.curriculumVitaeSendRecord;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import cn.iocoder.yudao.module.member.api.curriculumVitaeSendRecord.dto.CurriculumVitaeSendRecordPageReqDTO;
import cn.iocoder.yudao.module.member.controller.admin.job.vo.MemberJobUpdateReqVO;
import cn.iocoder.yudao.module.member.dal.dataobject.company.CompanyDO;
import cn.iocoder.yudao.module.member.dal.dataobject.company.CompanyUserDO;
import cn.iocoder.yudao.module.member.dal.dataobject.curriculumVitaeSendRecord.CurriculumVitaeSendInviteRecordDO;
import cn.iocoder.yudao.module.member.dal.dataobject.curriculumVitaeSendRecord.CurriculumVitaeSendRecordGroupDO;
import cn.iocoder.yudao.module.member.dal.dataobject.job.MemberJobDO;
import cn.iocoder.yudao.module.member.dal.dataobject.newsStudyInfo.NewsStudyInfoDO;
import cn.iocoder.yudao.module.member.dal.dataobject.studentCurriculumVitae.StudentCurriculumVitaeDO;
import cn.iocoder.yudao.module.member.dal.dataobject.studentEducationalExperience.StudentEducationalExperienceDO;
import cn.iocoder.yudao.module.member.dal.mysql.studentEducationalExperience.StudentEducationalExperienceMapper;
import cn.iocoder.yudao.module.member.service.company.CompanyService;
import cn.iocoder.yudao.module.member.service.job.MemberJobService;
import cn.iocoder.yudao.module.member.service.studentCurriculumVitae.StudentCurriculumVitaeService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.member.controller.admin.curriculumVitaeSendRecord.vo.*;
import cn.iocoder.yudao.module.member.dal.dataobject.curriculumVitaeSendRecord.CurriculumVitaeSendRecordDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.member.convert.curriculumVitaeSendRecord.CurriculumVitaeSendRecordConvert;
import cn.iocoder.yudao.module.member.dal.mysql.curriculumVitaeSendRecord.CurriculumVitaeSendRecordMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.*;

/**
 * 简历投递记录 Service 实现类
 *
 * @author 谭万全
 */
@Service
@Validated
public class CurriculumVitaeSendRecordServiceImpl implements CurriculumVitaeSendRecordService {

    @Resource
    private CurriculumVitaeSendRecordMapper curriculumVitaeSendRecordMapper;
    @Resource
    private CompanyService companyService;
    @Resource
    private StudentCurriculumVitaeService studentCurriculumVitaeService;
    @Resource
    private MemberJobService memberJobService;

    @Resource
    private StudentEducationalExperienceMapper studentEducationalExperienceMapper;
    @Override
    public Long createCurriculumVitaeSendRecord(CurriculumVitaeSendRecordCreateReqVO createReqVO) {
        // 插入
        CurriculumVitaeSendRecordDO curriculumVitaeSendRecord = CurriculumVitaeSendRecordConvert.INSTANCE.convert(createReqVO);
        curriculumVitaeSendRecord.setSourceAgent(ServletUtils.getSourceAgent());
        TenantUtils.execute(createReqVO.getTenantId(), () -> {
            //执行创建企业insert
            curriculumVitaeSendRecordMapper.insert(curriculumVitaeSendRecord);
        });

        MemberJobDO memberJobDO=memberJobService.getJob(createReqVO.getJobId());
        if(memberJobDO!=null){
            Integer count=memberJobService.addCount(createReqVO.getJobId(),"post",1);
            memberJobDO.setPostCount(count);
            updateJobCount(memberJobDO);
        }
        // 返回
        return curriculumVitaeSendRecord.getId();
    }
    @Async
    public void updateJobCount(MemberJobDO updateReqVO) {
        memberJobService.updateJob(updateReqVO);
    }

    @Override
    public void updateCurriculumVitaeSendRecord(CurriculumVitaeSendRecordUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateCurriculumVitaeSendRecordExists(updateReqVO.getId());
        // 更新
        CurriculumVitaeSendRecordDO updateObj = CurriculumVitaeSendRecordConvert.INSTANCE.convert(updateReqVO);
        curriculumVitaeSendRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteCurriculumVitaeSendRecord(Long id) {
        // 校验存在
        this.validateCurriculumVitaeSendRecordExists(id);
        // 删除
        curriculumVitaeSendRecordMapper.deleteById(id);
    }

    @Override
    public void deleteCurriculumVitaeSendRecords(Collection<Long> ids) {
        curriculumVitaeSendRecordMapper.deleteBatchIds(ids);
    }

    private void validateCurriculumVitaeSendRecordExists(Long id) {
        if (curriculumVitaeSendRecordMapper.selectById(id) == null) {
            throw exception(CURRICULUM_VITAE_SEND_RECORD_NOT_EXISTS);
        }
    }

    @Override
    public CurriculumVitaeSendRecordDO getCurriculumVitaeSendRecord(Long id) {
        CurriculumVitaeSendRecordDO curriculumVitaeSendRecordDO=curriculumVitaeSendRecordMapper.selectById(id);
        if(curriculumVitaeSendRecordDO!=null) {
            List<StudentEducationalExperienceDO> studentEducationalExperienceDOS = studentEducationalExperienceMapper.selectListByStudentId(curriculumVitaeSendRecordDO.getResumeId());
            curriculumVitaeSendRecordDO.setEducationalExperience(studentEducationalExperienceDOS);
        }
        return curriculumVitaeSendRecordDO;
    }

    @Override
    public CurriculumVitaeSendRecordDO getCurriculumVitaeSendRecordByPara(Long studentId, Long jobId, Long companyId, Long resumId) {
        return curriculumVitaeSendRecordMapper.getCurriculumVitaeSendRecordByPara(studentId,jobId,companyId,resumId);
    }

    @Override
    public List<CurriculumVitaeSendRecordDO> getCurriculumVitaeSendRecordList(Collection<Long> ids) {
        return curriculumVitaeSendRecordMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<CurriculumVitaeSendRecordDO> getCurriculumVitaeSendRecordPage(CurriculumVitaeSendRecordPageReqVO pageReqVO) {
        PageResult<CurriculumVitaeSendRecordDO> curriculumVitaeSendRecordDOPage=curriculumVitaeSendRecordMapper.selectPage(pageReqVO);
        return curriculumVitaeSendRecordDOPage;
    }

    @Override
    public PageResult<CurriculumVitaeSendRecordDO> getCurriculumVitaeSendRecordPage1(CurriculumVitaeSendRecordPageReqVO pageReqVO) {
        IPage<CurriculumVitaeSendRecordDO> mpPage = MyBatisUtils.buildPage(pageReqVO);
        // 转换返回
        Map<String, Object> params = new HashMap<>();
        if(null!=pageReqVO.getRelationType()){
            params.put("relationType",pageReqVO.getRelationType());
        }
        if(null!=pageReqVO.getBeginPostDate()){
            String date1 = DateUtils.format(pageReqVO.getBeginPostDate(), DateUtils.FORMAT_YEAR_MONTH_DAY);
            params.put("beginPostDate",date1+" 00:00:00");
        }
        if(null!=pageReqVO.getEndPostDate()){
            String date1 = DateUtils.format(pageReqVO.getEndPostDate(), DateUtils.FORMAT_YEAR_MONTH_DAY);
            params.put("endPostDate",date1+" 23:59:59");
        }
        if(StringUtils.isNotBlank(pageReqVO.getJobStatus())){
            params.put("jobStatus",pageReqVO.getJobStatus());
        }
        if(StringUtils.isNotBlank(pageReqVO.getStatus())){
            params.put("status",pageReqVO.getStatus());
        }
        if(null!=pageReqVO.getJobId()){
            params.put("jobId",pageReqVO.getJobId());
        }
        if(StringUtils.isNotBlank(pageReqVO.getSource())){
            params.put("source",pageReqVO.getSource());
        }
        if(StringUtils.isNotBlank(pageReqVO.getStudentName())){
            params.put("studentName",pageReqVO.getStudentName());
        }
        if(null !=pageReqVO.getCollectStatus()){
            params.put("collectStatus",pageReqVO.getCollectStatus());
        }
        Long loginUserId = WebFrameworkUtils.getLoginUserId();
        params.put("loginUserId",loginUserId);
        List<CurriculumVitaeSendRecordDO> curriculumVitaeSendRecordList = curriculumVitaeSendRecordMapper.getCurriculumVitaeSendRecordList(mpPage, params);
        mpPage.setRecords(curriculumVitaeSendRecordList);
        return new PageResult<>(mpPage.getRecords(), mpPage.getTotal());
    }

    @Override
    public List<CurriculumVitaeSendRecordDO> getCurriculumVitaeSendRecordList(CurriculumVitaeSendRecordExportReqVO exportReqVO) {
        return curriculumVitaeSendRecordMapper.selectList(exportReqVO);
    }

    @Override
    public List<Long> getCurriculumVitaeSendRecordIdList(CurriculumVitaeSendRecordPageReqVO pageReqVO) {
        List<CurriculumVitaeSendRecordDO> curriculumVitaeSendRecordDOS=curriculumVitaeSendRecordMapper.selectList(pageReqVO);
        List<Long> ids=new ArrayList<>();
        for (CurriculumVitaeSendRecordDO curriculumVitaeSendRecordDO:curriculumVitaeSendRecordDOS
             ) {
                ids.add(curriculumVitaeSendRecordDO.getId());
        }

        return ids;
    }

    @Override
    public PageResult<CurriculumVitaeSendRecordGroupDO> checkInfoByJob(CurriculumVitaeSendRecordGroupPageReqVO pageReqVO) {

        Integer total = curriculumVitaeSendRecordMapper.countCheckInfoByJob(pageReqVO);
        if (total <= 0) {
            return PageResult.empty();
        }
        List<CurriculumVitaeSendRecordGroupDO> curriculumVitaeSendRecordGroupDOList = curriculumVitaeSendRecordMapper.checkInfoByJob(pageReqVO);
        return PageResult.build(curriculumVitaeSendRecordGroupDOList, total);
    }

    @Override
    public PageResult<CurriculumVitaeSendRecordDO> getpageByJob(CurriculumVitaeSendRecordPageReqVO pageVO) {
        return curriculumVitaeSendRecordMapper.selectPage(pageVO);
    }

    @Override
    public PageResult<CurriculumVitaeSendInviteRecordDO> getpageByStudent(CurriculumVitaeSendRecordPageReqVO pageVO) {
        Integer total = curriculumVitaeSendRecordMapper.countPageByStudent(pageVO);
        if (total <= 0) {
            return PageResult.empty();
        }
        List<CurriculumVitaeSendInviteRecordDO> curriculumVitaeSendRecordDOList=curriculumVitaeSendRecordMapper.selectPageByStudent(pageVO);
        return PageResult.build(curriculumVitaeSendRecordDOList, total);

    }

    @Override
    public Long sendStudentCurriculumVitae(Long companyId, Long studentCurriculumVitaeId,Long jobId,String remark) {
        CurriculumVitaeSendRecordDO create=curriculumVitaeSendRecordMapper.selectOne("resume_id",studentCurriculumVitaeId,"job_id",jobId);
        if(create!=null){
            throw exception(STUDENT_CURRICULUM_VITAE_SEND_IS_EXISTS);
        }
        StudentCurriculumVitaeDO studentCurriculumVitaeDO=studentCurriculumVitaeService.getStudentCurriculumVitae(studentCurriculumVitaeId);
        CompanyDO companyDO=companyService.getCompany(companyId,0);
        MemberJobDO memberJobDO=memberJobService.getJob(jobId,1);
        CurriculumVitaeSendRecordDO creaCurrDo=pageCurriculumVitaeSendInviteRecordDO(studentCurriculumVitaeDO,companyDO,memberJobDO,remark);
        creaCurrDo.setSourceAgent(ServletUtils.getSourceAgent());
        TenantUtils.execute(companyDO.getTenantId(), () -> {
            //执行创建企业insert
            curriculumVitaeSendRecordMapper.insert(creaCurrDo);
        });
        Integer postCount=memberJobDO.getPostCount();
        if(postCount==null){
            postCount=0;
        }else{
            postCount++;
        }
        memberJobDO.setPostCount(postCount);
        memberJobService.updateJob(memberJobDO);
        return creaCurrDo.getId();
    }

    @Override
    public Long noOpenCount(Long studentId) {
        return curriculumVitaeSendRecordMapper.noOpenCount(studentId);
    }


    CurriculumVitaeSendRecordDO pageCurriculumVitaeSendInviteRecordDO(StudentCurriculumVitaeDO studentCurriculumVitaeDO,CompanyDO companyDO,MemberJobDO memberJobDO,String remark){
        CurriculumVitaeSendRecordDO curriculumVitaeSendRecordDO=new CurriculumVitaeSendRecordDO();
        curriculumVitaeSendRecordDO.setStudentId(studentCurriculumVitaeDO.getStudentId());
        curriculumVitaeSendRecordDO.setStudentName(studentCurriculumVitaeDO.getStudentName());
        curriculumVitaeSendRecordDO.setJobId(memberJobDO.getId());
        curriculumVitaeSendRecordDO.setJobName(memberJobDO.getJobName());
        curriculumVitaeSendRecordDO.setCompanyId(companyDO.getId());
        curriculumVitaeSendRecordDO.setCompanyName(companyDO.getCompanyName());
        curriculumVitaeSendRecordDO.setPostDate(new Date());
        LoginUser user=SecurityFrameworkUtils.getLoginUser();
        curriculumVitaeSendRecordDO.setPublisherId(user.getId());
        curriculumVitaeSendRecordDO.setCity(memberJobDO.getCity());
        curriculumVitaeSendRecordDO.setPublisherName(user.getUsername());
        curriculumVitaeSendRecordDO.setResumeId(studentCurriculumVitaeDO.getId());
        curriculumVitaeSendRecordDO.setSource("2");
        curriculumVitaeSendRecordDO.setPolitical(studentCurriculumVitaeDO.getPolitical());
        curriculumVitaeSendRecordDO.setSex(studentCurriculumVitaeDO.getSex());
        curriculumVitaeSendRecordDO.setBirthday(studentCurriculumVitaeDO.getBirthday());
        curriculumVitaeSendRecordDO.setLiveCity(studentCurriculumVitaeDO.getLiveCity());
        curriculumVitaeSendRecordDO.setGraduateTime(studentCurriculumVitaeDO.getGraduateTime());
        curriculumVitaeSendRecordDO.setIdentify(studentCurriculumVitaeDO.getIdentify());
        curriculumVitaeSendRecordDO.setStudentPictureUrl(studentCurriculumVitaeDO.getStudentPictureUrl());
        curriculumVitaeSendRecordDO.setNativePlace(studentCurriculumVitaeDO.getNativePlace());
        curriculumVitaeSendRecordDO.setClan(studentCurriculumVitaeDO.getClan());
        curriculumVitaeSendRecordDO.setPhoneNumber(studentCurriculumVitaeDO.getPhoneNumber());
        curriculumVitaeSendRecordDO.setEmail(studentCurriculumVitaeDO.getEmail());
        curriculumVitaeSendRecordDO.setUniversityName(studentCurriculumVitaeDO.getUniversityName());
        curriculumVitaeSendRecordDO.setSpecialty(studentCurriculumVitaeDO.getSpecialty());
        curriculumVitaeSendRecordDO.setEducationLeve(studentCurriculumVitaeDO.getEducationLeve());
        curriculumVitaeSendRecordDO.setEducation(studentCurriculumVitaeDO.getEducation());
        curriculumVitaeSendRecordDO.setGrade(studentCurriculumVitaeDO.getGrade());
        curriculumVitaeSendRecordDO.setDiploma(studentCurriculumVitaeDO.getDiploma());
        curriculumVitaeSendRecordDO.setUniversityStartDate(studentCurriculumVitaeDO.getUniversityStartDate());
        curriculumVitaeSendRecordDO.setUniversityEndDate(studentCurriculumVitaeDO.getUniversityEndDate());
        curriculumVitaeSendRecordDO.setTargetIndustry(studentCurriculumVitaeDO.getTargetIndustry());
        curriculumVitaeSendRecordDO.setTargetCity(studentCurriculumVitaeDO.getTargetCity());
        curriculumVitaeSendRecordDO.setLowestSalary(memberJobDO.getLowestSalary());
        curriculumVitaeSendRecordDO.setHighestSalary(memberJobDO.getHighestSalary());
        curriculumVitaeSendRecordDO.setCourses(studentCurriculumVitaeDO.getCourses());
        curriculumVitaeSendRecordDO.setWorkExperience(studentCurriculumVitaeDO.getWorkExperience());
        curriculumVitaeSendRecordDO.setProjectExperience(studentCurriculumVitaeDO.getProjectExperience());
        curriculumVitaeSendRecordDO.setLanguageAbility(studentCurriculumVitaeDO.getLanguageAbility());
        curriculumVitaeSendRecordDO.setSpecialtyAbility(studentCurriculumVitaeDO.getSpecialtyAbility());
        curriculumVitaeSendRecordDO.setSpecialtyAbility(studentCurriculumVitaeDO.getSpecialtyAbility());
        curriculumVitaeSendRecordDO.setCertificates(studentCurriculumVitaeDO.getCertificates());
        curriculumVitaeSendRecordDO.setPracticeExperience(studentCurriculumVitaeDO.getPracticeExperience());
//        curriculumVitaeSendRecordDO.setEducationalExperience(studentCurriculumVitaeDO.getEducationalExperience());
        curriculumVitaeSendRecordDO.setInternshipDesire(studentCurriculumVitaeDO.getInternshipDesire());
        curriculumVitaeSendRecordDO.setUserId(studentCurriculumVitaeDO.getStudentId());
        curriculumVitaeSendRecordDO.setDeptId(memberJobDO.getDeptId());
        curriculumVitaeSendRecordDO.setWorkPeriod(memberJobDO.getWorkPeriod());
        curriculumVitaeSendRecordDO.setSendType("2");
        curriculumVitaeSendRecordDO.setRemark(remark);
        return curriculumVitaeSendRecordDO;
    }
}
